/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2021-07-30 07:52:12
 * @LastEditors: GGB
 * @LastEditTime: 2021-07-30 11:09:49
 */
import 'package:flutter/material.dart';
import 'package:flutter_faster_study/apps/health_master/model/exercise.dart';
import 'package:flutter_faster_study/apps/health_master/model/exercise_set.dart';

import 'components/video_controls_widget.dart';
import 'components/video_player_widget.dart';

class ExerciseScreen extends StatefulWidget {
  const ExerciseScreen({Key key, @required this.exerciseSet}) : super(key: key);
  final ExerciseSet exerciseSet;

  @override
  _ExerciseScreenState createState() => _ExerciseScreenState();
}

class _ExerciseScreenState extends State<ExerciseScreen> {
  final controller = PageController();
  Exercise currrentExercise;

  @override
  void initState() {
    super.initState();
    currrentExercise = widget.exerciseSet.exercises.first;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose();
    print("销毁page controller");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        title: Text(currrentExercise.name),
        centerTitle: true,
        elevation: 0,
      ),
      extendBodyBehindAppBar: true,
      body: Stack(
        children: [
          buildVideos(),
          Positioned(
            bottom: 20,
            right: 58,
            left: 58,
            child: VideoControlsWiget(
              exercise: currrentExercise,
              onNextVideo: () => controller.nextPage(
                duration: Duration(microseconds: 300),
                curve: Curves.easeIn,
              ),
              onRewindVideo: () => controller.previousPage(
                duration: Duration(microseconds: 300),
                curve: Curves.easeIn,
              ),
              onTogglePlaying: (bool isPlaying) {
                setState(() {
                  isPlaying
                      ? currrentExercise.controller.play()
                      : currrentExercise.controller.pause();
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget buildVideos() => PageView(
        controller: controller,
        onPageChanged: (index) => setState(() {
          currrentExercise = widget.exerciseSet.exercises[index];
        }),
        children: widget.exerciseSet.exercises
            .map(
              (exercise) => VideoPlayerWidget(
                exercise: exercise,
                onInitialized: () => setState(() {}),
              ),
            )
            .toList(),
      );
}
